/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.base;

import org.webos.java.root.*;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URLEncoder;
import java.util.Properties;
import javax.servlet.ServletContext;
import org.urchr.web.db.DBUtil;
import org.webos.java.base.Session;
import org.webos.java.base.fs.FileManager;
import org.webos.java.base.users.DBUserProvider;
import org.webos.java.base.UserManager;
import org.webos.java.base.SessionManager;



/**
 *
 * @author Kostya
 */

class ProxyAuthenticator extends Authenticator{

    private String userName;
    private String password;

    public ProxyAuthenticator(String aUserName, String aPassword) {
        userName = aUserName;
        password = aPassword;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password.toCharArray());
    }

}
public class SystemManager {

    private static Properties properties = new Properties();

    static void init(ServletContext aContext){
        String appPath = aContext.getRealPath(Constants.APPLICATION_FS_PATH);
//        if(!DBUtil.exportSchema(appPath+"/db.export")){
//            Log.error(null, "Can't export schema to file");
//        }
        try {
            properties.load(new FileInputStream(aContext.getRealPath(Constants.SYSTEM_CONFIG_PATH)));
        } catch (Throwable t) {
            Log.error(null, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        String cachePath = aContext.getRealPath(Constants.CACHE_FS_PATH);
        FileManager.FILE_STORAGE_PATH = aContext.getRealPath(Constants.FILE_STORAGE_PATH);
        UserManager.setProvider(new DBUserProvider());
        Log.debug(null, "Filter init "+appPath+", ", aContext.getContextPath(), UserManager.getProvider());
        ApplicationManager.appContextPath = getProperty("application.context", aContext.getContextPath());
        ApplicationManager.loadApplications(appPath);
        ApplicationManager.reloadApplications(appPath, cachePath);
        //Load properties
        for (int i = 0; i < Log.codes.length; i++) {
            String code = Log.codes[i];
            if(code.equals(getProperty("debug.level", "DEBUG")))
                Log.setMaxLevel(i);
        }

    }

    public static String getProperty(String aName, String aDefault){
        if(properties==null)
            return aDefault;
        return properties.getProperty(aName, aDefault);
    }

    public static boolean isProperty(String aName, String aValue){
        String value = getProperty(aName, null);
        if(null==value){
            return aValue==null;
        }
        return value.equalsIgnoreCase(aValue);
    }

    public static void setupProxy(Session aSession){
        if(isProperty("proxy.enable", "yes")){
            System.setProperty("http.proxyHost", getProperty("proxy.hostname", ""));
            System.setProperty("https.proxyHost", getProperty("proxy.hostname", ""));
            System.setProperty("http.proxyPort", getProperty("proxy.port", "8080"));
            System.setProperty("https.proxyPort", getProperty("proxy.port", "8080"));
            Authenticator.setDefault(new ProxyAuthenticator(getProperty("proxy.username", ""), getProperty("proxy.password", "")));
        }else{
            System.setProperty("http.proxyHost", "");
            System.setProperty("https.proxyHost", "");
            System.setProperty("http.proxyPort", "");
            System.setProperty("https.proxyPort", "");
        }
    }

    static void destroy(){
        //Terminate all apps
        for (int i = 0; i < SessionManager.getSessionCount(); i++) {
            Session session = SessionManager.getSessionAt(i);
            session.reset();
            for (Application application : session.applications) {
                application.terminate();
            }
        }
    }

	public static String prepareTextForView(String data, boolean replaceTags){
		String result = data;
        if(result==null)
            return "";
		if(replaceTags)
			result = result.replace("<", "&lt;").replace(">", "&gt;");
		return result.replace("\n", "<br/>").replace("\r", "");
	}

}
